var THROTTLE_INTERVAL = 0.2;	// in seconds;

// ----------------------------------------------

var p_script_start, p_script_end;

$(document).ready(function() {
	p_script_start = new Date().getTime();
	$("<style type='text/css'>" +
		".indented { margin-left: 36px !important; }" +
		"#filter { float: right; }" +
		"#progressbar { width: 700px; height: 40px; margin: auto;}" +
		".ui-progressbar-value { -moz-transition-property: width; -webkit-transition-property: width; -o-transition-property: width;"+
						   "-moz-transition-duration: 1s; -webkit-transition-duration: 1s; -o-transition-duration: 1s; border-radius: 6px;}" +
		"#status { text-align: center; height: 40px; margin-top: 60px; margin-bottom: -40px; line-height: 40px;"+
				 "font-family: VAGRundschriftD-Lig,'Arial Rounded MT Light','Arial Rounded MT',Arial,sans-serif; font-size: 15px; }" +
		".label-section { display: none; }" +
		"p.timetaken { font-size: 0.9em; color: #999; }" + //(window.DEBUG ? "" : "p.timetaken { display: none; }") +
		"</style>").appendTo("head");

	$.getScript('https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js', function() {
		$('head').append('<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/themes/cupertino/jquery-ui.css" type="text/css" />');
		$('<div id="status"></div><div id="progressbar"></div>').insertAfter($('h1'));
		$("#progressbar").progressbar({ value: 1 });

		$("#status").text("Loading streets...")
		$("#progressbar").progressbar("option", "value", 2);

		$.ajax({ url: LISTING_SCRIPT, dataType: "script"
			, error: function() { if (typeof(locations) === 'undefined') { $("#status").text("Oops! The hamsters have gone amok. Please reload!"); return; } }
			, success: function(data, textStatus) {
				$("#status").text("Adding streets...");
				$("#progressbar").progressbar("option", "value", 4);

				// If we're going to add streets into their proper lists, we ought to label each region's list
				$("h3").each(function () {
					var name = $(this).html().replace(/\s+/g, "").toLowerCase();
					$(this).next().attr("id", name);
				});

				// Create a temporary place to put new streets
				var TEMP_REGIONS = {
					'xalanga': { 'name': 'Xalanga', 'after': 'zhambu'}
					,'salatu': { 'name': 'Salatu', 'after': 'xalanga'}
					,'muufo': { 'name': 'Muufo', 'after': 'salatu'}
				};
				for (regionSlug in TEMP_REGIONS) {
					region = TEMP_REGIONS[regionSlug];
					if ($('#' + regionSlug).length == 0) {
						$('#' + region.after).parent().after('<div class="section label-section"><h3>' + region.name + '</h3><ul class="list" id="' + regionSlug + '" style="margin: -20px 0;"></ul>');
					}
				}
				$('div.section ul.list').each(function(i, e) {
					var list = $(e);
					
					var checkVisitLink = $('<a id="btnCheckVisit_' + list.attr('id') + '" title="Show visited status (visited: light grey, unvisited: bold)" href="javascript: void(0);" class="checkVisit button-tiny button-minor" region="' + list.attr('id') + '" style="position: absolute; top: 20px; right: 0px; font-size: 11px;">Check Visits</a>');
					checkVisitLink.click(function(e) {
						var btn = $(this);
						if (btn.html() == 'Checking...') { return; }
						btn.html('Checking...');
						$('#' + $(e.target).attr('region') + ' a').each(function(index, element) {
							var href = window.location.protocol + '//' + window.location.host + $(this).attr("href");
							var link = $(this);
							link.css("font-weight", "normal");
							link.css("color", "#005C73");
							scrapeCount++;
							setTimeout(scrapePage, (index+1)*0.7*1000, [href, link, btn]);
						});
					});
					
					list.before(checkVisitLink);
				});
				// Create a place to put multiplayer quests.
				$('.container').append('<div class="section label-section"><h3>Multiplayer Quests</h3><ul id="multiplayerquests" class="list" style="margin: -20px 0;"></ul>');

				// Create a place to put odds and ends.
				$('.container').append('<div class="section label-section"><h3>Other</h3><ul id="other" class="list" style="margin: -20px 0;"></ul>');

				var haveRedundancies = false;

				var listed = new Array();
				$('ul.list a').each(function() {
					listed.push($(this).attr("href").split("/")[2]);
				});
            
				var sortIndex = new Object();
                                
				// Loop through locations and add links.                
				for (tsid in locations) {
					// Only add a link if the street hasn't already been listed already.
					if (listed.indexOf(tsid) == -1){
						var region = locations[tsid].region;
						var regionEl = ($("#" + region).length > 0) ? $("#" + region) : $("#other");
						var sortname = (locations[tsid].sortname ? 'sortname="' + locations[tsid].sortname + '"' : '');
						var newItem = $('<li><a ' + sortname + ' href="/locations/' + tsid + '/">'+locations[tsid].name+'</a></li>');

						// For readability, let's indent housing streets.
						//if (locations[tsid].name.match(/block|model|towers|villa|lofts|apartments|cottages|manor|subway station|bureaucratic|machine/gi)) {
						if (locations[tsid].name.match(/block|model|towers|villa|lofts|loft|apartments|cottages|manor|subway station|machine/gi)) {
							if(locations[tsid].name.match(/subway station/gi)) {
								newItem.addClass("subway");
							}
							newItem.addClass("substreet indented");
						}

						// Insert the street in the list, where it should be alphabetically.
						var added = false;
						var name = (locations[tsid].sortname) ? locations[tsid].sortname : locations[tsid].name;

						$("li", regionEl).slice(sortIndex[region]).each(function(index){
							var listItem = $(this).children(":first");
							var listItemName = (listItem.attr('sortname') ? listItem.attr('sortname') : listItem.text());
							if (listItemName > name) {
								newItem.insertBefore($(this));
								if(sortIndex[region] == undefined)
									sortIndex[region] = 0;
								if(!locations[tsid].sortname)
									sortIndex[region] += index+1;
								added = true;
								return false;
							}
						});

						// And if it doesn't get added, just throw it on the end.
						if (!added) {
							newItem.appendTo(regionEl);
						}
					} else if (window.DEBUG) {
						// Prune JSON.
						haveRedundancies = true;
						delete locations[tsid];
					}
				}
				if(window.DEBUG && haveRedundancies) {
					var html = '<p><label for="json">Prune your JSON!</label><br/><textarea style="width: auto !important;" cols="80" rows="5" readonly id="json"></textarea></p>';
					$(html).insertAfter($('h1'));
					$("#json").text('var locations = (' + JSON.stringify(locations, null, 4) + ');');
				}

				$("ul.list li").append("<span class='qty'></span><span class='after'></span>")

				// Add filter drop down
				$("<div id='filter'>Filter: <select disabled='true'><option id='all'>All Streets</option><option id='project'>Active Projects</option>"+
					"<option id='subway'>Subway Stations</option><optgroup label='Shrines' id='shrines'></optgroup>"+
					"<optgroup label='Vendors' id='vendors'></optgroup><optgroup label='Resources' id='resources'></optgroup></select></div>").insertAfter("#progressbar");
				$("#filter").hide();
				$("#filter select").change(function(e) {
					var id = e.target.options[e.target.selectedIndex].id;
					$(".qty").html("");
					$(".label-section").show();

					if(id == "all") {
						$("ul.list li").show();
						$(".substreet").addClass("indented");
						return;
					}

					$(".substreet").removeClass("indented");
					$("ul.list li." + id).show();
					$("ul.list li." + id + " a").each(function() {
						if($(this).attr(id)) {
							$(this).parent().find(".qty").html(" (" + $(this).attr(id) + ")");
						}
					});
					$("ul.list li:not(." + id +")").hide();
					$(".label-section").each(function(index) {
					  if($(this).find("li:visible").length == 0) {
						  $(this).hide();
					  } else {
						  $(this).show();
					  }
					});
				});
				checkList(locations);
			} // success
		});   // $.ajax
	});

	function checkList(locations) {
		// Set as desination business.
		$("ul.list li").hover(
			function() {
				// We don't want to readd the link if we've already succeeded and faded out, but haven't done a mouseout yet.
				if (!($(this).hasClass("succeeded"))) {
					var url = $(this).find("a")[0].attributes["href"].value; // url to POST to

					// We also don't want to add a link if we've already got a link or a link that's been clicked!
					if ($(this).find(".noRemove").length == 0) {
						$(this).find(".after").append("<span id='destination'> &#8212; <span>Set as destination</span></span>");
						$(this).find("#destination span").css({"cursor": "pointer", "color": "#005C73", "font-weight": "bold"});
						$(this).find("#destination span").click(function() {
							// When clicked, say it's loading and submit the POST.
							var link = $(this);
							link.unbind("click");
							link.addClass("noRemove");
							link.html("Loading...");
							link.css({"cursor": "progress"});
							$.ajax({
								type: "POST",
								url: url,
								data: {set_as_destination: 1},
								success: function() {
									link.html("Success!");
									link.css({"cursor": "default", "color": "green"});
									link.parent().parent().parent().addClass("succeeded");
									link.parent().delay(500).fadeOut(function(){ $(this).remove(); });
								},
								error: function() {
									link.html("Error!");
									link.css({"cursor": "default", "color": "red"});
									// I recognize that it shouldn't be called "succeeded" when it's an error, but piss off.
									link.parent().parent().parent().addClass("succeeded");
									link.parent().delay(500).fadeOut(function(){ $(this).remove(); });
								}
							});
						});
					}
				}
			},
			function() {
				// Remove the link only when it's a link, and not "Loading" or something.
				if ($(this).find(".noRemove").length == 0) {
					$(this).find("#destination").remove();
					$(this).removeClass("succeeded");
				}
			}
		);

		// Init.
		total = $("ul.list a").length;
		$("#status").text("Checking streets...")
		var progressBar = $("#progressbar");
		progressBar.progressbar("value", 5);

		// Start the check.
		$("ul.list a").each(function(index, element) {
			var link = $(this);
			link.attr("target", "_blank");	// open up location pages in new tab to avoid accidental clicks
			var appendage = link.parent().find(".after");
			var tsid = $(this).attr("href").split("/")[2];
			setTimeout(getStreetInfo, (index+1)*THROTTLE_INTERVAL*1000, [tsid, link, appendage, index, progressBar]);
		});
	}	// function checkList(locations)

	var checked = 0, havebeen = 0;
	var total = 0;
	var loadError = false;
    
	function getStreetInfo(params) {
		var tsid = params[0] + '';
		var link = params[1];		
		var appendage = params[2];
		var index = params[3];
		var progressBar = params[4];

		api_call('locations.streetInfo', { street_tsid: tsid }, function(r) {
			checked++;
			p_script_end = new Date().getTime();
			$("#status").text("Checking streets... " + checked + " of " + total + "." + (window.DEBUG ? " Time elapsed: " + Math.round((p_script_end-p_script_start)/1000) + " sec" : ""));
			progressBar.progressbar("value", 5+(100*checked/total));
			if (!r.ok) {
				console.log('Error calling api for ' + tsid + ': ' + r.error);
				if (!window.DEBUG) { link.parent().remove(); } else { appendage.append(' &#8212; <span style="color:red;font-weight: bold">404!</span>'); }
				link.parent().addClass('hamsters');
				if (window.DEBUG) { appendage.append(' &#8212; <span style="color:red;font-weight: bold">ERR: ' + r.error + '</span>'); }
				return;
			}
			var activeProjects = r.active_project;
			// Add a note if there's an active project.
			if (activeProjects) {
				appendage.append(' &#8212; <span style="color:green;font-weight: bold">Active Project!</span>')
				link.parent().addClass("project");
			}

			// Pull the resource information.
			var info = r.features;
			$.each(info, function(index, feature) {
				switch(feature.substr(0, 4)) {
					case "A sh":
					case "A Sh":
						var god = $('<span>' + feature + '</span>').find("b").text();
						if(god == "Ti") {
							god = "Tii";
						}
						link.parent().addClass(god);
						if($("#" + god).length == 0) {
							var newItem = $("<option id='" + god + "'>" + god + "</option>")
							var added = false;
							$("#shrines option").each(function(index) {
								if ($(this).text() > god) {
									newItem.insertBefore($(this));
									added = true;
									return false;
								}
							});
							if(!added) {
								newItem.appendTo("#shrines");
							}

						}
						break;
					default:
						$('<span>' + feature + '</span>').find("b").each(function() {
							var kind = "resources";
							var re = $(this).text().match(/([0-9]+ |A |An )?(.*)/);
							var resource = re[2];
							var quantity = re[1];
							if(resource.substr(-11) == " for mining") {
								resource = resource.substr(0, (resource.length - 11));
							} else if(resource.substr(-7) == " Vendor") {
								resource = resource.substr(0, (resource.length - 7));
								kind = "vendors";
							}
							var id = resource.substr(0,3);
							if(id == "Hou") {
								return;
							}
							if(quantity) {
								quantity = quantity.substr(0, (re[1].length -1));
								if(quantity.match(/[0-9]+/)) {
									link.attr(id, quantity);
								}
							}

							link.parent().addClass(id);
							if($("#" + id).length == 0) {
								var newItem = $("<option id='" + id + "'>" + resource + "</option>");
								var added = false;
								$("#" + kind + " option").each(function(index) {
									if ($(this).text() > resource) {
										newItem.insertBefore($(this));
										added = true;
										return false;
									}
								});
								if(!added) {
									newItem.appendTo("#" + kind);
								}
							} else {
								if($("#" + id).text().length < resource.length) {
									$("#" + id).text(resource);
								}
							}
						});
						break;
				}
			});

			// Enable filter drop down once done
			if(index == (total -1)) {
				$("#status").text("Finishing...")
				progressBar.progressbar("value", 100);
				$(".label-section").show();
				$("#status").hide();
				$("#progressbar").hide();
				$("#filter").show();
				$("#filter select").removeAttr("disabled");
				$("<p class='timetaken'>Time taken: " + format_sec((p_script_end-p_script_start)/1000) + "</p>").insertAfter($("#filter"));
			}
		});	// api_call('locations.streetInfo');
	}
	
	var scrapeCount = 0;
    function scrapePage(params) {
		var href = params[0];
		var link = params[1];
		var btn = params[2];
		$.get(href, function(data) {
			scrapeCount--;
			var page = $(data);
			var visits = page.find('.section.label-section h3:contains("Visits")').parent();			
			// Bold if the street is unvisited, gray out if it has been visited.
			if(visits.html() == null) {
				//loadError = true;
			} else if (visits.html().match(/never been here before/)) {
				link.css("font-weight", "bold");
				link.css("color", "#005C73");
			} else {
				link.css("font-weight", "normal");
				link.css("color", "darkgray");
			}
			
			if (scrapeCount == 0) {
				btn.html('Check Visits');
			}
		});	// $.get
    }	// function scrapePage(link)

});
